package com.project.web.admin.utils.freemarker.directive;

import com.project.web.admin.utils.freemarker.FreemarkerUtils;
import com.project.model.core.StdCode;
import com.project.web.admin.service.core.StdCodeService;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 标准编码指令
 */
@Component("stdCodeDirective")
public class StdCodeDirective extends BaseDirective {

    //参数：是否显示不可用的,默认为false
    private final static String SHOW_PARAM_NAME = "all";
    //参数：编码类型的codeType
    private final static String TYPE_PARAM_NAME = "codeType";
    //参数：是否使用map，默认为true
    private final static String IS_MAP_PARAM_NAME = "isMap";

    //map变量名称
    private final static String VARIABLE_NAME = "codeMap";

    //list变量名称
    private final static String LIST_VARIABLE_NAME = "codeList";

    @Resource(name = "stdCodeServiceImpl")
    private StdCodeService stdCodeService;

    @SuppressWarnings("unchecked")
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {

        //获取编码类型字符串
        String codeType = FreemarkerUtils.getParameter(TYPE_PARAM_NAME, String.class, params);

        //默认只显示可用的
        Boolean isShowDisabled = FreemarkerUtils.getParameter(SHOW_PARAM_NAME, Boolean.class, params);
        if (isShowDisabled == null) {
            isShowDisabled = false;
        }

        //默认使用map封装
        Boolean isMap = FreemarkerUtils.getParameter(IS_MAP_PARAM_NAME, Boolean.class, params);
        if (isMap == null) {
            isMap = true;
        }

        //区分需要的数据结构为map还是list
        if (isMap) {
            if (StringUtils.isEmpty(codeType)) {
                setLocalVariable(VARIABLE_NAME, new LinkedHashMap<String, String>(), env, body);
                return;
            }

            //从缓存中获取
            Map<String, String> map = stdCodeService.getMap(codeType, isShowDisabled);

            if (map == null) {
                map = new LinkedHashMap<String, String>();
            }

            setLocalVariable(VARIABLE_NAME, map, env, body);

        } else {

            if (StringUtils.isEmpty(codeType)) {
                setLocalVariable(LIST_VARIABLE_NAME, new ArrayList<StdCode>(), env, body);
                return;
            }

            //获取list
            List<StdCode> list = stdCodeService.findList(codeType, isShowDisabled);

            if (list == null) {
                list = new ArrayList<StdCode>();
            }

            setLocalVariable(LIST_VARIABLE_NAME, list, env, body);
        }

    }
}
